let scrolling = true; // 控制是否继续滚动
let bottomCount = 0;  // 连续到底部次数
const MAX_BOTTOM_RETRIES = 300; // 最大到底部重试次数
const SCROLL_DELAY = 100; // 帧间延迟
const SCROLL_RATIO = 0.8; // 每次滚动占可滚动高度的比例

/**
 * 平滑滚动元素
 * @param {Element|Window} el
 */
function smoothScroll(el) {
    if (!scrolling) return;

    const isWindow = el === window;
    const maxScrollTop = isWindow
        ? document.documentElement.scrollHeight - window.innerHeight
        : el.scrollHeight - el.clientHeight;

    const currentScroll = isWindow ? window.scrollY : el.scrollTop;

    if (currentScroll < maxScrollTop) {
        // 动态计算滚动步长，保证每次滚动约为总可滚动高度的 20%
        const remainingScroll = maxScrollTop - currentScroll;
        const scrollStep = Math.max(1, remainingScroll * SCROLL_RATIO); // 至少滚动1px

        if (isWindow) {
            window.scrollBy(0, scrollStep);
        } else {
            el.scrollTop += scrollStep;
        }

        setTimeout(() => requestAnimationFrame(() => smoothScroll(el)), SCROLL_DELAY);
    } else {
        bottomCount++;
        if (bottomCount >= MAX_BOTTOM_RETRIES) {
            // 到达底部次数超过阈值，回到顶部重试
            if (isWindow) {
                window.scrollTo(0, 0);
            } else {
                el.scrollTop = 0;
            }
            bottomCount = 0;
        }
        // 继续滚动
        setTimeout(() => requestAnimationFrame(() => smoothScroll(el)), SCROLL_DELAY);
    }
}

/**
 * 判断元素是否可滚动
 * @param {Element} el
 */
function isScrollable(el) {
    const style = getComputedStyle(el);
    return (style.overflow === 'auto' || style.overflow === 'scroll' ||
            style.overflowX === 'auto' || style.overflowX === 'scroll' ||
            style.overflowY === 'auto' || style.overflowY === 'scroll') &&
           el.scrollHeight > el.clientHeight;
}

/**
 * 初始化滚动所有可滚动元素
 */
function initScrolling() {
    // window 滚动
    smoothScroll(window);

    // body 及所有子元素滚动
    document.querySelectorAll('body, body *').forEach(el => {
        if (isScrollable(el)) {
            smoothScroll(el);
        }
    });
}

// 观察 DOM 新增或移除元素
const observer = new MutationObserver(() => {
    document.querySelectorAll('body, body *').forEach(el => {
        if (isScrollable(el)) {
            smoothScroll(el);
        }
    });
});

observer.observe(document.body, { childList: true, subtree: true });

// 初始化滚动
initScrolling();
